<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">培训管理</span>
      <el-button
          type="primary"
          style="float: right; margin-top: 13px;"
          @click="beforeAddTraining">
        新增培训
      </el-button>
    </div>

    <!-- 培训弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose" width="50%">
      <el-form label-width="100px" :model="trainingForm" :rules="rules" ref="trainingForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训标题" prop="title">
              <el-input v-model="trainingForm.title" placeholder="请输入培训标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训讲师" prop="trainer">
              <el-input v-model="trainingForm.trainer" placeholder="请输入讲师姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start_time">
              <el-date-picker
                  v-model="trainingForm.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  style="width:100%"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end_time">
              <el-date-picker
                  v-model="trainingForm.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  style="width:100%"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训地点" prop="location">
              <el-input v-model="trainingForm.location" placeholder="请输入培训地点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训状态" prop="status">
              <el-select v-model="trainingForm.status" placeholder="请选择状态" style="width:100%">
                <el-option label="未开始" :value="1"></el-option>
                <el-option label="进行中" :value="2"></el-option>
                <el-option label="已结束" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="培训内容" prop="content">
          <el-input
              type="textarea"
              :rows="4"
              v-model="trainingForm.content"
              placeholder="请输入培训内容">
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitTraining">保存</el-button>
      </template>
    </el-dialog>

    <!-- 培训查询 -->
    <el-card style="margin: 20px;height: 70px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="培训标题">
          <el-input v-model="searchForm.title" placeholder="请输入培训标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" :value="1"></el-option>
            <el-option label="进行中" :value="2"></el-option>
            <el-option label="已结束" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadTrainingList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 培训列表 -->
    <el-card style="margin: 20px;">
      <el-table :data="trainingList">
        <el-table-column label="编号" type="index" align="center"></el-table-column>
        <el-table-column label="培训标题" prop="title" align="center"></el-table-column>
        <el-table-column label="讲师" prop="trainer" align="center"></el-table-column>
        <el-table-column label="开始时间" prop="startTime" align="center"></el-table-column>
        <el-table-column label="结束时间" prop="endTime" align="center"></el-table-column>
        <el-table-column label="地点" prop="location" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button link type="text" @click="editTraining(row)">编辑</el-button>
            <el-button link type="text" @click="deleteTraining(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          style="margin-top: 20px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
import qs from "qs";

export default {
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '新增培训',
      trainingForm: {
        id: null,
        title: '',
        trainer: '',
        startTime: '',
        endTime: '',
        location: '',
        content: '',
        status: 1
      },
      rules: {
        title: [{ required: true, message: '请输入培训标题', trigger: 'blur' }],
        trainer: [{ required: true, message: '请输入讲师姓名', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, validator: this.validateEndTime, trigger: 'change' }],
        location: [{ required: true, message: '请输入培训地点', trigger: 'blur' }],
        content: [{ required: true, message: '请输入培训内容', trigger: 'blur' }]
      },
      searchForm: {
        title: '',
        status: null
      },
      trainingList: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    };
  },
  mounted() {
    this.loadTrainingList();
  },
  methods: {
    // 加载培训列表
    loadTrainingList() {
      const data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        ...this.searchForm
      });

      axios.get(this.$BASE_URL +'/v1/training/list?'+data)
          .then(res => {
            if (res.data.state === 2000) {
              this.trainingList = res.data.data.trainingList;
              this.pagination.total = res.data.data.total;
            }else {
              Message.error(res.data.message || '操作失败');
            }
          })
    },

    // 提交培训数据
    submitTraining() {
      this.$refs.trainingForm.validate(valid => {
        if (valid) {
          axios.post(this.$BASE_URL +'/v1/training/save', qs.stringify(this.trainingForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('操作成功');
                  this.dialogVisible = false;
                  this.loadTrainingList();
                }else {
                  Message.error(res.data.message || '操作失败');
                }
              });
        }
      });
    },

    // 新增培训
    beforeAddTraining() {
      this.dialogTitle = '新增培训';
      this.trainingForm = {
        id: null,
        title: '',
        trainer: '',
        startTime: '',
        endTime: '',
        location: '',
        content: '',
        status: 1
      };
      this.dialogVisible = true;
    },

    // 编辑培训
    editTraining(row) {
      this.dialogTitle = '编辑培训信息';
      this.trainingForm = {
        id: row.id,
        title: row.title,
        trainer: row.trainer,
        startTime: row.startTime,
        endTime: row.endTime,
        location: row.location,
        content: row.content,
        status: row.status
      };
      this.dialogVisible = true;
    },

    // 删除培训
    deleteTraining(id) {
      this.$confirm('确定删除该培训记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        axios.post(this.$BASE_URL +`/v1/training/delete/${id}`)
            .then(res => {
              if (res.data.state === 2000) {
                Message.success('删除成功');
                this.loadTrainingList();
              }else{
                Message.error(res.data.message || '删除失败');
              }
            });
      });
    },

    // 重置查询
    resetSearch() {
      this.searchForm = {
        title: '',
        status: null
      };
      this.pagination.current = 1;
      this.loadTrainingList();
    },

    // 验证结束时间
    validateEndTime(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择结束时间'));
      } else if (new Date(value) <= new Date(this.trainingForm.start_time)) {
        callback(new Error('结束时间必须晚于开始时间'));
      } else {
        callback();
      }
    },

    // 格式化状态显示
    formatStatus(status) {
      const map = { 1: '未开始', 2: '进行中', 3: '已结束' };
      return map[status] || '未知状态';
    },

    // 状态标签样式
    getStatusTagType(status) {
      const types = { 0: 'info', 1: 'primary', 2: 'success', 3: 'danger' };
      return types[status] || '';
    },

    // 分页处理
    handleSizeChange(size) {
      this.pagination.size = size;
      this.loadTrainingList();
    },

    handleCurrentChange(current) {
      this.pagination.current = current;
      this.loadTrainingList();
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.$nextTick(() => {
        if (this.$refs.trainingForm) {
          this.$refs.trainingForm.resetFields();
        }
      });
    }
  }
};
</script>

<style scoped>

</style>